package com.ctg.payroll2.action.empadmin;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.ctg.payroll2.bean.EmployeeInfo;
import com.ctg.payroll2.bean.po.CsEmpAccount;
import com.ctg.payroll2.bean.po.PbEmployee;
import com.ctg.payroll2.bean.po.PbEmployeeTmp;
import com.ctg.payroll2.bean.po.SysUser;
import com.ctg.payroll2.service.empadmin.EmpAdminIndexService;
import com.ctg.payroll2.service.xlsImport.XlsImportService;
import com.ctg.payroll2.util.Constants;
import com.ctg.platform.core.security.SpringSecurityManager;
import com.ctg.platform.core.security.Exception.SecurityException;
import com.ctg.platform.core.security.entity.Account;
import com.ctg.platform.util.Page;
import com.ctg.platform.util.Parse;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class EmpAdminIndexAction extends ActionSupport {
	private static final long serialVersionUID = 6921952143708071327L;

	private boolean success;

	private Page result;

	private String msg;

	private EmployeeInfo employeeInfo;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public EmployeeInfo getEmployeeInfo() {
		return employeeInfo;
	}

	public void setEmployeeInfo(EmployeeInfo employeeInfo) {
		this.employeeInfo = employeeInfo;
	}

	public Page getResult() {
		return result;
	}

	public void setResult(Page result) {
		this.result = result;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	private EmpAdminIndexService empAdminIndexService;

	private XlsImportService xlsImportService;

	public void setXlsImportService(XlsImportService xlsImportService) {
		this.xlsImportService = xlsImportService;
	}

	public void setEmpAdminIndexService(
			EmpAdminIndexService empAdminIndexService) {
		this.empAdminIndexService = empAdminIndexService;
	}

	/**
	 * 获取雇员信息
	 * 
	 * @return
	 */
	public String queryEmployeeInfo() {
		Integer employee_id = null;

		HttpServletRequest request = ServletActionContext.getRequest();
		employee_id = Parse.toInteger(request.getParameter("employee_id"));

		if (employee_id == null) {
			this.success = false;
			msg = "抱歉,无法获取到正确的员工编号";
			return SUCCESS;
		}
		try {
			employeeInfo = empAdminIndexService.getEmployeeInfo(employee_id);
		} catch (Exception e) {
			e.printStackTrace();
			this.success = false;
			return SUCCESS;
		}
		this.success = true;
		return SUCCESS;
	}

	/**
	 * 保存雇员信息
	 * 
	 * @return
	 */
	public String saveEmployeeInfo() {
		String baseInfoPanelParam = null;
		String socialSecurityNumberPanelParam = null;
		String bankCardNumberPanelParam = null;

		HttpServletRequest request = ServletActionContext.getRequest();
		baseInfoPanelParam = Parse.toString(request
				.getParameter("baseInfoPanelParam"), false);
		socialSecurityNumberPanelParam = Parse.toString(request
				.getParameter("socialSecurityNumberPanelParam"), false);
		bankCardNumberPanelParam = Parse.toString(request
				.getParameter("bankCardNumberPanelParam"), false);

		// WebApplicationContext wac =
		// WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		try {
			empAdminIndexService.saveEmployeeInfo(((SysUser) request
					.getSession().getAttribute(Constants.CURRENT_USER))
					.getCompanyCode(), baseInfoPanelParam,
					socialSecurityNumberPanelParam, bankCardNumberPanelParam);
		} catch (Exception sqle) {
			sqle.printStackTrace();
		}

		return SUCCESS;
	}

	public static String[] splitStringToStringArray(String args) {
		JSONArray json = JSONArray.fromObject(args);
		Object[] ss = json.toArray();
		String[] array = new String[ss.length];
		for (int i = 0; i < ss.length; i++) {
			// System.out.println("====="+ss[i]);
			String s = ss[i] + "";
			array[i] = s;
		}
		return array;
	}

	public String queryAllEmpAdmin() {
		try {
			String emp_cs_code = null;
			String name = null;
			Integer is_valid = null;
			Integer out_jobdate = null;
			String start_date = null;
			String end_date = null;
			Integer start = null;
			Integer limit = null;
			Integer employStatus = null;
			Integer orgchat_id = null;

			HttpServletRequest request = ServletActionContext.getRequest();
			SysUser su = (SysUser) request.getSession().getAttribute(
					Constants.CURRENT_USER);
			String company_code = su.getCompanyCode();
			emp_cs_code = Parse.toString(request.getParameter("emp_cs_code"),
					false);
			name = Parse.toString(request.getParameter("name"), false);
			orgchat_id = Parse.toInteger(request.getParameter("orgchat_id"));
			employStatus = Parse.toInteger(request.getParameter("status"), 4);
			if (employStatus == 1) {
				is_valid = 1;
				out_jobdate = 1;
			} else if (employStatus == 2) {
				is_valid = 0;
				out_jobdate = 1;
			} else if (employStatus == 0) {
				is_valid = 1;
				out_jobdate = 0;
			} else {
				is_valid = null;
				out_jobdate = null;
			}

			if (request.getParameter("startdt") != null) {
				start_date = request.getParameter("startdt");
			}
			if (request.getParameter("enddt") != null) {
				end_date = request.getParameter("enddt");
			}
			start = Parse.toInteger(request.getParameter("start"), 0);
			limit = Parse.toInteger(request.getParameter("limit"),
					Constants.DEFAULT_PAGE_SIZE);

			result = empAdminIndexService.getAllEmpAdminByPaging(company_code,
					emp_cs_code, name, is_valid, out_jobdate, orgchat_id,
					start_date, end_date, start, limit);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String deletePbEmployee() {
		String employee = null;
		HttpServletRequest request = ServletActionContext.getRequest();
		employee = request.getParameter("employee_id");
		String[] array = splitStringToStringArray(employee);
		List<PbEmployee> list = new ArrayList();

		PbEmployee pbEmployee = null;
		try {
			for (int i = 0; i < array.length; i++) {
				pbEmployee = new PbEmployee();
				pbEmployee.setEmployee_id(Integer.parseInt(array[i]));
				list.add(pbEmployee);
			}
			empAdminIndexService.deleteEmployee(list);

		} catch (SQLException e) {

			e.printStackTrace();
		}
		return SUCCESS;
	}

	// -----------------------------------------------雇员权限分配开始-------------------------------------------

	private String checkCode;

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	private SpringSecurityManager springSecurityManager;

	public void setSpringSecurityManager(
			SpringSecurityManager springSecurityManager) {
		this.springSecurityManager = springSecurityManager;
	}

	private List<com.ctg.platform.core.security.entity.Role> list;

	public List<com.ctg.platform.core.security.entity.Role> getList() {
		return list;
	}

	public void setList(List<com.ctg.platform.core.security.entity.Role> list) {
		this.list = list;
	}

	// 给雇员分配权限时检查帐户名是否可用
	public String checkLoginCode() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String loginCode = request.getParameter("loginCode");
		try {
			SysUser sysUser = (SysUser) request.getSession().getAttribute(
					Constants.CURRENT_USER);
			Account account1 = springSecurityManager.getAccountByUserName(
					loginCode, sysUser);
			if (account1 == null) {
				msg = "0";
			} else
				msg = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;

	}

	public String createLoginCode() {
		HttpServletRequest request = ServletActionContext.getRequest();
		SysUser sysUser = (SysUser) request.getSession().getAttribute(
				Constants.CURRENT_USER);
		String loginCode = request.getParameter("loginCode");
		String empId = request.getParameter("empId");
		String pwd = request.getParameter("pwd");
		String name = request.getParameter("name");
		String updateOrInsert = request.getParameter("updateOrInsert");
		String strs = request.getParameter("strs");
		strs = strs.substring(12, strs.length());
		String[] array;
		array = strs.split("%2C");
		Account acc = new Account();
		acc.setUsername(loginCode);
		acc.setPassword(pwd);
		acc.setDisabled("0");
		CsEmpAccount csEmpAccount = new CsEmpAccount();
		csEmpAccount.setCompany_code(sysUser.getCompanyCode());
		csEmpAccount.setEmployee_id(Integer.parseInt(empId));
		try {
			if (updateOrInsert.equals("insert")) {
				empAdminIndexService.insertCsEmpAccount(acc, sysUser, array,
						csEmpAccount, name);
				msg = "true";
			} else {
				Account account2 = springSecurityManager.getAccountByUserName(
						loginCode, sysUser);
				if (springSecurityManager.revokeRoleFromAccount(account2
						.getId(), sysUser)) {
					Boolean b = springSecurityManager.assignRoleForAccount(
							account2, array, sysUser);
					msg = b.toString();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String queryEmpRoll() {
		HttpServletRequest request = ServletActionContext.getRequest();
		SysUser sysUser = (SysUser) request.getSession().getAttribute(
				Constants.CURRENT_USER);
		String empId = request.getParameter("empId");
		try {
			CsEmpAccount cea = empAdminIndexService.queryEmproll(Integer
					.parseInt(empId));
			Account account11 = springSecurityManager.getAccountByAccountId(cea
					.getLogin_code(), sysUser);
			list = springSecurityManager.getRoleListByLoginName(account11
					.getUsername());
			msg = account11.getUsername();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	// -----------------------------------------------雇员权限分配结束-------------------------------------------

	private List<PbEmployeeTmp> pbEmployeeList;

	private List badList;

	public List getBadList() {
		return badList;
	}

	public void setBadList(List badList) {
		this.badList = badList;
	}

	public List<PbEmployeeTmp> getPbEmployeeList() {
		return pbEmployeeList;
	}

	public void setPbEmployeeList(List<PbEmployeeTmp> pbEmployeeList) {
		this.pbEmployeeList = pbEmployeeList;
	}

	/**
	 * 雇员信息导入
	 * 
	 * @return
	 */
	private String strCm;

	private String fields;

	public String getStrCm() {
		return strCm;
	}

	public void setStrCm(String strCm) {
		this.strCm = strCm;
	}

	public String getFields() {
		return fields;
	}

	public void setFields(String fields) {
		this.fields = fields;
	}

	public String importByXls() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			SysUser su = (SysUser) request.getSession().getAttribute(
					Constants.CURRENT_USER);
			String uploadInfo = request.getParameter("uploadInfo");
			String filePath = "";
			String erroeStr = "";
			if ("" != uploadInfo) {
				filePath = uploadInfo.replace("\\\\", "\\");
			}
			HashMap paraMap = new HashMap();
			HashMap mapping = new HashMap();
			String ex_interfaceid = request.getParameter("ex_interfaceid");
			String ex_publictype = request.getParameter("ex_publictype");
			paraMap.put("ex_interfaceid", ex_interfaceid);
			paraMap.put("ex_publictype", ex_publictype);
			mapping = xlsImportService.getMappingToBean(paraMap);
			fields = "[";
			strCm = "";
			for (Iterator<Entry<String, String>> it = mapping.entrySet()
					.iterator(); it.hasNext();) {
				Entry<String, String> ent = it.next();
				String nameAndMapping = ent.getValue();
				String header = ent.getKey();
				fields += "{name:'" + nameAndMapping + "',mapping:'"
						+ nameAndMapping + "'},";
				strCm += "{header: \"" + header + "\", dataIndex: '"
						+ nameAndMapping + "'},";
			}
			fields = fields.substring(0, fields.length() - 1) + "]";
			strCm = strCm.substring(0, strCm.length() - 1);
			if ("" != filePath) {
				// 获取xls的数据
				Map<String, List> impMap = xlsImportService
						.importDataByJxlToBean(filePath, PbEmployeeTmp.class,
								mapping);
				if (null != impMap) {
					pbEmployeeList = impMap.get("Good.Records");
					badList = impMap.get("Bad.Records");
					if (pbEmployeeList.size() > 0) {
						// 将xls的数据插入到临时表
						xlsImportService.importDataList(impMap
								.get("Good.Records"));
						HashMap<String, Object> paraMap1 = new HashMap<String, Object>();
						List<Map<String, Object>> isOnlyEmp = xlsImportService
								.isOnlyByempCsCode();
						if (isOnlyEmp.size() < 1) {
							if (su.getCompanyCode() != null) {
								// 雇员导入从临时表到正式表之前修改 政治面貌,部门,婚姻状况等下拉框形式的值为对应数据库的值
								xlsImportService.updateEmpcomboxMapping();
								paraMap1
										.put("companyCode", su.getCompanyCode());
								// 临时表到正式表的插入
								xlsImportService.insertJTmp2Formal(
										PbEmployeeTmp.class, paraMap1);
								msg = "导入完成";
							} else {
								throw new RuntimeException("客户编号为空,无法导入!");
							}
						} else {
							for (Map<String, Object> map : isOnlyEmp) {
								erroeStr = "此次导入有 " + map.get("ISONLY")
										+ " 条重复编号为" + map.get("CS_EMPCODE")
										+ " 的数据,导入终止!";
							}
							msg = erroeStr;
						}
					}
				} /*
					 * else { System.out.println("getDataIsNull"); }
					 */
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

	/**
	 * goodlist
	 */
	private List<Map<String, String>> glist;

	/**
	 * badlist
	 */
	private List<Map<String, String>> blist;

	public List<Map<String, String>> getGlist() {
		return glist;
	}

	public void setGlist(List<Map<String, String>> glist) {
		this.glist = glist;
	}

	public List<Map<String, String>> getBlist() {
		return blist;
	}

	public void setBlist(List<Map<String, String>> blist) {
		this.blist = blist;
	}

	/**
	 * 薪资导入demo
	 * 
	 * @return
	 */
	public String impSo() {
		msg = "开始导入";
		HttpServletRequest request = ServletActionContext.getRequest();
		String uploadInfo = request.getParameter("uploadInfo");
		String filePath = "";
		if ("" != uploadInfo) {
			filePath = uploadInfo.replace("\\\\", "\\");
		}
		HashMap paraMap = new HashMap();
		HashMap mapping = new HashMap();
		String ex_interfaceid = request.getParameter("ex_interfaceid");
		String ex_publictype = request.getParameter("ex_publictype");
		String payClassId = request.getParameter("payClassId");
		paraMap.put("ex_interfaceid", ex_interfaceid);
		paraMap.put("ex_publictype", ex_publictype);
		mapping = xlsImportService.getMappingToBean(paraMap);
		fields = "[";
		strCm = "";
		for (Iterator<Entry<String, String>> it = mapping.entrySet().iterator(); it
				.hasNext();) {
			Entry<String, String> ent = it.next();
			String nameAndMapping = ent.getValue();
			String header = ent.getKey();
			fields += "{name:'" + nameAndMapping + "',mapping:'"
					+ nameAndMapping + "'},";
			strCm += "{header: \"" + header + "\", dataIndex: '"
					+ nameAndMapping + "'},";
		}
		fields = fields.substring(0, fields.length() - 1) + "]";
		strCm = strCm.substring(0, strCm.length() - 1);
		// System.out.println(fields);
		// System.out.println(strCm);
		if ("" != filePath) {
			try {
				Map<String, List<Map<String, String>>> map = xlsImportService
						.importDataByJxlToList(filePath, mapping);
				List<Map<String, String>> goodlist = map.get("Good.Records");
				if (goodlist.size() > 0) {
					xlsImportService.executeSql(xlsImportService
							.createSql(goodlist));
					xlsImportService.update_imp_table();
					// 需要一个payClassId
					HashMap<String, List> resultMap = xlsImportService
							.createsql2compensation(null, Integer
									.parseInt(payClassId), "payment");
					blist = resultMap.get(Constants.BAD_LIST);
					glist = goodlist;
					msg = "导入完成";
				}
			} catch (Throwable e) {
				e.printStackTrace();
			} finally {
				// xlsImportService.droptable();
			}
		}
		return SUCCESS;
	}

	/**
	 * 社保导入
	 * 
	 * @return
	 */
	public String importSocial() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String uploadInfo = request.getParameter("uploadInfo");
		String filePath = "";
		if ("" != uploadInfo) {
			filePath = uploadInfo.replace("\\\\", "\\");
		}
		HashMap paraMap = new HashMap();
		HashMap mapping = new HashMap();
		String ex_interfaceid = request.getParameter("ex_interfaceid");
		String ex_publictype = request.getParameter("ex_publictype");
		paraMap.put("ex_interfaceid", ex_interfaceid);
		paraMap.put("ex_publictype", ex_publictype);
		mapping = xlsImportService.getMappingToBean(paraMap);
		fields = "[";
		strCm = "";
		for (Iterator<Entry<String, String>> it = mapping.entrySet().iterator(); it
				.hasNext();) {
			Entry<String, String> ent = it.next();
			String nameAndMapping = ent.getValue();
			String header = ent.getKey();
			fields += "{name:'" + nameAndMapping + "',mapping:'"
					+ nameAndMapping + "'},";
			strCm += "{header: \"" + header + "\", dataIndex: '"
					+ nameAndMapping + "'},";
		}
		fields = fields.substring(0, fields.length() - 1) + "]";
		strCm = strCm.substring(0, strCm.length() - 1);
		// System.out.println(fields);
		// System.out.println(strCm);
		if ("" != filePath) {
			try {
				Map<String, List<Map<String, String>>> map = xlsImportService
						.importDataByJxlToList(filePath, mapping);
				List<Map<String, String>> goodlist = map.get("Good.Records");
				if (goodlist.size() > 0) {
					xlsImportService.executeSql(xlsImportService
							.createSql(goodlist));
					xlsImportService.update_imp_table();
					HashMap<String, List> resultMap = xlsImportService
							.createsql2compensation(null, null, "social");
					xlsImportService.droptable();
					blist = resultMap.get(Constants.BAD_LIST);
					glist = goodlist;
				}
			} catch (Throwable e) {
				e.printStackTrace();
			} finally {
				// xlsImportService.droptable();
			}
		}
		return SUCCESS;
	}

}
